using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ctsu.Admin.Forms;
using ctsu.BaseForms;
using ctsu.Data;
using ctsu.Security;
using ctsu.Shared;
using Microsoft.Practices.EnterpriseLibrary.Data;

using Syncfusion.Windows.Forms.Tools;


namespace ctsu.Admin.BusLogic
{
	public class BLFormQAImpl : BLFormBaseImpl
	{
		enum SearchTypes { Standard, OutpatientVisits, Admissions, Patient, Protocol, Investigator };
		private SearchTypes _searchType = SearchTypes.Standard;
		private DataTable _dtCheckData;
		private DataTable _dtCheckFields;
		private ArrayList _alrcItems;
		private Hashtable _htrcItems;
		private Hashtable _htQaGroups;

		#region control references
		private Syncfusion.Windows.Forms.Tools.DateTimePickerAdv _visitDate;
		private Syncfusion.Windows.Forms.Tools.DateTimePickerAdv _incidentDate;
		private ComboBox _visitType;
		private ComboBox _qaFilingPerson;
		private GroupBox _gbx1;
		private GroupBox _gbx2;
		private TextBox _visitID;
		private TextBox _patient;
		private TextBox _mrn;
		private TextBox _patientName;
		private TextBox _protocol;
		//private TextBox _spid;
		private TextBox _protocolNumber;
		private TextBox _investigator;
		private TextBox _stickAttempts;
		private TextBox _painScore;
		private TextBox _recoveryTime;
		private TextBox _patientReactionOther;
		private TextBox _painInterventionOther;
		private TextBox _ivLocationOther;
		private ComboBox _ivLocation;
		private ComboBox _patientReaction;
		private ComboBox _painIntervention;
		private Button _btnVisit;
		private Panel _pnlComments;
		private Panel _pnl2;
		private Panel _pnlNotify;
		#endregion control references

		#region construct & initialize
		public BLFormQAImpl(FormMain formMain, FormBase form, FormInfoBase formInfo, DataTable tableSchema, Permission formSecurity, Hashtable configData)
			: base(formMain, form, formInfo, tableSchema, formSecurity, configData)
		{
		}

		protected override void _vcManager_OnAfterHookEvents()
		{
			_visitDate = (DateTimePickerAdv)Forms.Utils.GetControlByName("VisitDate", this._form.Controls);
			_incidentDate = (DateTimePickerAdv)Forms.Utils.GetControlByName("IncidentDate", this._form.Controls);
			_visitType = (ComboBox)Forms.Utils.GetControlByName("VisitType", this._form.Controls);
			_qaFilingPerson = (ComboBox)Forms.Utils.GetControlByName("QaFilingPerson", this._form.Controls);
			_gbx1 = (GroupBox)Forms.Utils.GetControlByName("gbx1", this._form.Controls);
			_gbx2 = (GroupBox)Forms.Utils.GetControlByName("gbx2", this._form.Controls);
			_visitID = (TextBox)Forms.Utils.GetControlByName("VisitID", this._form.Controls);
			_patient = (TextBox)Forms.Utils.GetControlByName("Patient", this._form.Controls);
			_mrn = (TextBox)Forms.Utils.GetControlByName("MRN", this._form.Controls);
			_patientName = (TextBox)Forms.Utils.GetControlByName("PatientName", this._form.Controls);
			_protocol = (TextBox)Forms.Utils.GetControlByName("Protocol", this._form.Controls);
			//_spid = (TextBox)Forms.Utils.GetControlByName("SPID", this._form.Controls);
			_protocolNumber = (TextBox)Forms.Utils.GetControlByName("ProtocolNumber", this._form.Controls);
			_investigator = (TextBox)Forms.Utils.GetControlByName("Investigator", this._form.Controls);
			_btnVisit = (Button)Forms.Utils.GetControlByName("btnVisit", this._form.Controls);
			_pnlComments = (Panel)Forms.Utils.GetControlByName("pnlComments", this._form.Controls);
			_pnl2 = (Panel)Forms.Utils.GetControlByName("pnl2", this._form.Controls);
			_pnlNotify = (Panel)Forms.Utils.GetControlByName("pnlNotify", this._form.Controls);
			_stickAttempts = (TextBox)Forms.Utils.GetControlByName("StickAttempts", this._form.Controls);
			_stickAttempts.KeyPress += new KeyPressEventHandler(Forms.Utils.txtNumWholePos_KeyPress);
			_painScore = (TextBox)Forms.Utils.GetControlByName("PainScore", this._form.Controls);
			_painScore.KeyPress += new KeyPressEventHandler(Forms.Utils.txtNumWholePos_KeyPress);
			_recoveryTime = (TextBox)Forms.Utils.GetControlByName("RecoveryTime", this._form.Controls);
			_recoveryTime.KeyPress += new KeyPressEventHandler(Forms.Utils.txtNumWholePos_KeyPress);
			_painIntervention = (ComboBox)Forms.Utils.GetControlByName("PainIntervention", this._form.Controls);
			_patientReaction = (ComboBox)Forms.Utils.GetControlByName("PatientReaction", this._form.Controls);
			_ivLocation = (ComboBox)Forms.Utils.GetControlByName("IVLocation", this._form.Controls);
			_painInterventionOther = (TextBox)Forms.Utils.GetControlByName("PainInterventionOther", this._form.Controls);
			_patientReactionOther = (TextBox)Forms.Utils.GetControlByName("PatientReactionOther", this._form.Controls);
			_ivLocationOther = (TextBox)Forms.Utils.GetControlByName("IVLocationOther", this._form.Controls);
			_painIntervention.SelectionChangeCommitted += new EventHandler(_painIntervention_SelectionChangeCommitted);
			_patientReaction.SelectionChangeCommitted += new EventHandler(_patientReaction_SelectionChangeCommitted);
			_ivLocation.SelectionChangeCommitted += new EventHandler(_ivLocation_SelectionChangeCommitted);
		}

		void _ivLocation_SelectionChangeCommitted(object sender, EventArgs e)
		{
			_ivLocationOther.Enabled = false;
			_ivLocationOther.Text = "";
			if (_ivLocation.Text == "Other")
				_ivLocationOther.Enabled = true;
		}

		void _patientReaction_SelectionChangeCommitted(object sender, EventArgs e)
		{
			_patientReactionOther.Enabled = false;
			_patientReactionOther.Text = "";
			if (_patientReaction.Text == "Other")
				_patientReactionOther.Enabled = true;
		}

		void _painIntervention_SelectionChangeCommitted(object sender, EventArgs e)
		{
			_painInterventionOther.Enabled = false;
			_painInterventionOther.Text = "";
			if (_painIntervention.Text == "Other")
				_painInterventionOther.Enabled = true;
		}
		#endregion construct & initialize

		#region generic click and select
		public override void GenericClick(Control sender)
		{
			if (sender.Name == "btnVisit")
				SelectVisit();
		}

		private void SelectVisit()
		{
			StringBuilder sb = new StringBuilder();

			if (this._visitDate.IsNullDate)
			{
				sb.Append("You must first select a visit date");
				MessageBox.Show(this._form, sb.ToString(), "Select Visit Date", MessageBoxButtons.OK, MessageBoxIcon.Stop);
				this._visitDate.Focus();
				return;
			}

			if (this._visitType.SelectedIndex == -1)
			{
				sb.Append("You must first select a visit type");
				MessageBox.Show(this._form, sb.ToString(), "Select Visit Type", MessageBoxButtons.OK, MessageBoxIcon.Stop);
				this._visitType.Focus();
				return;
			}

			int visitType = (int)this._visitType.SelectedValue;
			Cursor.Current = Cursors.WaitCursor;
			SearchInfo si;
			if (visitType == 1)
				si = (SearchInfo)this._formInfo.SearchFormInfo["OutPatientVisit"];
			else
				si = (SearchInfo)this._formInfo.SearchFormInfo["AdmissionVisit"];
			try
			{
				FormAncillaryAdmissionVisitSearch fs = new FormAncillaryAdmissionVisitSearch(si, this._visitDate.Value);
				fs.Text = "Visit Search";
				fs.ShowDialog(this._form);
				if (fs.DialogResult == DialogResult.OK)
				{
					VisitInfo vi = fs.SelectedVisitInfo;
					if (vi != null)
					{
						this._visitID.Text = vi.ID.ToString();
						this._visitDate.Value = vi.VisitDate;
						GetPatientData(vi.PatientID);
						GetProtocolData(vi.ProtocolID);
					}
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not display outPatient visit seach dialog!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Display Search Dialog Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void GetPatientData(int id)
		{
			StringBuilder sb = new StringBuilder();
			string sql = "SELECT ID, MRN, LastName + ', ' + FirstName AS Name FROM Patient WHERE ID = " + id;

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql);

				if (reader.Read())
				{
					this._patient.Text = reader.GetInt32(0).ToString();
					this._mrn.Text = reader.GetString(1);
					string name = "";
					if (!reader.IsDBNull(2))
						name = reader.GetString(2);
					this._patientName.Text = name;
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve patient!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Retrieve Patient Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
			}
		}

		private void GetProtocolData(int id)
		{
			StringBuilder sb = new StringBuilder();
			string sql = "SELECT p.ID, p.ProtocolNumber, " +
				" i.LastName + ', ' + i.FirstName AS Name " +
				" FROM Protocol p, ProtocolStaff ps, Investigator i " +
				" WHERE p.ID = " + id +
				" AND ps.ProtocolID = p.ID " +
				" AND ps.StaffTypeID = 1 " +
				" AND i.ID = ps.InvestigatorID";

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql);

				if (reader.Read())
				{
					this._protocol.Text = reader.GetInt32(0).ToString();
					//this._spid.Text = reader.GetInt32(1).ToString();
					this._protocolNumber.Text = reader.GetString(2);
					this._investigator.Text = reader.GetString(3);
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve protocol information!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Retrieve Protocol Information Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();				
			}
		}
		#endregion generic click and select

		#region search get and display
		public override void Search(object sender)
		{
			Control ctl = (Control)sender;
			ctl.Enabled = false;

			SelectQADialog sad = new SelectQADialog();
			sad.Text = this._formInfo.Name + " Search";
			sad.ShowDialog(this._formMain);
			switch (sad.SearchChoice)
			{
				case -1:
					break;
				case 0:
					SelectByStandard();
					break;
				case 1:
					SelectByOutpatientVisits();
					break;
				case 2:
					SelectByAdmissions();
					break;
				case 3:
					SelectByPatient();
					break;
				case 4:
					SelectByProtocol();
					break;
				case 5:
					SelectByInvestigator();
					break;
			}


			ctl.Enabled = true;

		}

		private void SelectByInvestigator()
		{
			StringBuilder sb = new StringBuilder();
			Cursor.Current = Cursors.WaitCursor;

			SearchInfo si = (SearchInfo)this._formInfo.SearchFormInfo["Investigator"];
			_searchType = SearchTypes.Investigator;
			try
			{
				FormSearchBase fs = (FormSearchBase)SearchUtils.GetSearchDialog(si);
				fs.Controller.ItemSelected += new BaseForms.BusinessLogicEvents.BLSelectedItemEventHandler(scr_ItemSelected);
				fs.Closing += new CancelEventHandler(fs_Closing);
				fs.Owner = this._form;
				IsSearchVisible = true;
				fs.Show();
			}
			catch (Exception ex)
			{
				sb.Append("Could not display protocol seach dialog!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Display Search Dialog Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void SelectByProtocol()
		{
			StringBuilder sb = new StringBuilder();
			Cursor.Current = Cursors.WaitCursor;

			SearchInfo si = (SearchInfo)this._formInfo.SearchFormInfo["Protocol"];
			_searchType = SearchTypes.Protocol;
			try
			{
				FormSearchBase fs = (FormSearchBase)SearchUtils.GetSearchDialog(si);
				fs.Controller.ItemSelected += new BaseForms.BusinessLogicEvents.BLSelectedItemEventHandler(scr_ItemSelected);
				fs.Closing += new CancelEventHandler(fs_Closing);
				fs.Owner = this._form;
				IsSearchVisible = true;
				fs.Show();
			}
			catch (Exception ex)
			{
				sb.Append("Could not display protocol seach dialog!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Display Search Dialog Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

		}

		private void SelectByPatient()
		{
			StringBuilder sb = new StringBuilder();
			Cursor.Current = Cursors.WaitCursor;

			SearchInfo si = (SearchInfo)this._formInfo.SearchFormInfo["Patient"];
			_searchType = SearchTypes.Patient;
			try
			{
				FormSearchBase fs = (FormSearchBase)SearchUtils.GetSearchDialog(si);
				fs.Controller.ItemSelected += new BaseForms.BusinessLogicEvents.BLSelectedItemEventHandler(scr_ItemSelected);
				fs.Closing += new CancelEventHandler(fs_Closing);
				fs.Owner = this._form;
				IsSearchVisible = true;
				fs.Show();
			}
			catch (Exception ex)
			{
				sb.Append("Could not display patient seach dialog!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Display Search Dialog Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

		}

		private void SelectByOutpatientVisits()
		{
			StringBuilder sb = new StringBuilder();
			Cursor.Current = Cursors.WaitCursor;

			SearchInfo si = (SearchInfo)this._formInfo.SearchFormInfo["VisitOutPatient"];
			_searchType = SearchTypes.OutpatientVisits;
			try
			{
				FormSearchBase fs = (FormSearchBase)SearchUtils.GetSearchDialog(si);
				fs.Controller.ItemSelected += new BaseForms.BusinessLogicEvents.BLSelectedItemEventHandler(scr_ItemSelected);
				fs.Closing += new CancelEventHandler(fs_Closing);
				fs.Owner = this._form;
				IsSearchVisible = true;
				fs.Show();
			}
			catch (Exception ex)
			{
				sb.Append("Could not display outpatient visit seach dialog!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Display Search Dialog Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

		}

		private void SelectByAdmissions()
		{
			StringBuilder sb = new StringBuilder();
			Cursor.Current = Cursors.WaitCursor;

			SearchInfo si = (SearchInfo)this._formInfo.SearchFormInfo["VisitAdmission"];
			_searchType = SearchTypes.Admissions;
			try
			{
				FormSearchBase fs = (FormSearchBase)SearchUtils.GetSearchDialog(si);
				fs.Controller.ItemSelected += new BaseForms.BusinessLogicEvents.BLSelectedItemEventHandler(scr_ItemSelected);
				fs.Closing += new CancelEventHandler(fs_Closing);
				fs.Owner = this._form;
				IsSearchVisible = true;
				fs.Show();
			}
			catch (Exception ex)
			{
				sb.Append("Could not display Outpatient Visit seach dialog!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Display Search Dialog Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

		}

		private void SelectByStandard()
		{
			StringBuilder sb = new StringBuilder();
			Cursor.Current = Cursors.WaitCursor;

			SearchInfo si = (SearchInfo)this._formInfo.SearchFormInfo["QualityAssurance"];

			try
			{
				FormSearchBase fs = (FormSearchBase)SearchUtils.GetSearchDialog(si);
				fs.Owner = this._form;
				fs.Controller.ItemSelected += new BaseForms.BusinessLogicEvents.BLSelectedItemEventHandler(sc_ItemSelected);
				fs.Closing += new CancelEventHandler(fs_Closing);
				IsSearchVisible = true;
				fs.Show();
			}
			catch (Exception ex)
			{
				sb.Append("Could not display out patient visit seach dialog!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Display Search Dialog Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private int SelectFromResults(int id, string recordType, string searchBy, string searchResultKey)
		{
			StringBuilder sb = new StringBuilder();
			Cursor.Current = Cursors.WaitCursor;

			SearchResultInfo si = (SearchResultInfo)this._formInfo.SearchResultInfo[searchResultKey];
			//SqlConnection conn = LoginForm.GetSqlConnection();
			try
			{
				//first see if there are any visits for this patient
				string sql = si.SqlCommand;
				if (sql.IndexOf("@@") > 0)
					sql = sql.Replace("@@", id.ToString());
				else
					sql += id;

				DataSet ds = DataAccess.GetDataSet(sql);
				DataTable dt = ds.Tables[0];
				if (dt.Rows.Count == 0)
				{
					MessageBox.Show("There are no " + recordType + " for " + searchBy + " id: " + id, "No " + recordType + " Found", MessageBoxButtons.OK, MessageBoxIcon.Information);
					return 0;
				}
				SearchUtils.SetColumnMeta(dt, si);
				FormSearchResultsBase fsr = (FormSearchResultsBase)SearchUtils.GetSearchResultsDialog(si, dt);
				fsr.Text = searchBy + " Search";
				fsr.Controller.BusinessLogic.ItemSelected += new BaseForms.BusinessLogicEvents.BLSelectedItemEventHandler(BusinessLogic_ItemSelected);
				fsr.Closing += new CancelEventHandler(fsr_Closing);
				fsr.Owner = this._form;
				fsr.Show();
				return 1;
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not retrieve select results.");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this._form, sb.ToString(), "Select Results Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return 0;
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();
			}
		}

		private void scr_ItemSelected(object sender, BLReturnIDEventArgs e)
		{
			string recordType = "";
			string searchBy = "";
			string searchResultsKey = "";

			switch (this._searchType)
			{
				case SearchTypes.Admissions:
					recordType = "QA records";
					searchBy = "Admission Visit";
					searchResultsKey = "AdmissionQA";
					break;
				case SearchTypes.OutpatientVisits:
					recordType = "QA records";
					searchBy = "Out Patient Visit";
					searchResultsKey = "OutpatientQA";
					break;
				case SearchTypes.Investigator:
					recordType = "QA records";
					searchBy = "Protocol";
					searchResultsKey = "ProtocolQA";
					break;
				case SearchTypes.Patient:
					recordType = "QA records";
					searchBy = "Patient";
					searchResultsKey = "PatientQA";
					break;
				case SearchTypes.Protocol:
					recordType = "QA records";
					searchBy = "Protocol";
					searchResultsKey = "ProtocolQA";
					break;
			}
			if (e.ID > 0)
				SelectFromResults(e.ID, recordType, searchBy, searchResultsKey);
		}

		private void BusinessLogic_ItemSelected(object sender, BLReturnIDEventArgs e)
		{
			if (e.ID > 0)
			{
				if (this.GetData(e.ID))
				{
					if (this.FormMode == EditMode.Load)
						SetFormMode(EditMode.Read);
				}
			}
		}

		private void fsr_Closing(object sender, CancelEventArgs e)
		{

		}

		private void sc_ItemSelected(object sender, BLReturnIDEventArgs e)
		{
			if (e.ID > 0)
			{
				Console.WriteLine("Selected ID: " + e.ID.ToString());
				if (GetData(e.ID))
				{
					if (this.FormMode == EditMode.Load)
						SetFormMode(EditMode.Read);
				}
			}
			else
				Console.WriteLine("ID: " + e.ID);
		}

		private void fs_Closing(object sender, CancelEventArgs e)
		{
			IsSearchVisible = false;
			this._form.btnSearch.Enabled = true;
		}
		#endregion search get and display


		#region display data
		public override void DisplayData()
		{
			base.DisplayData();

			DisplayCheckData();
			if (this._visitID.Text.Length > 0)
			{
				int visitID = Convert.ToInt32(this._visitID.Text);
				GetVisitPatientProtocolData(visitID);
			}
			else
				ClearNonFieldContextControls();

		}

		private void DisplayCheckData()
		{
			foreach (RowContext rc in this._alrcItems)
			{
				//disable controls while in read mode
				if (this._formMode == EditMode.Load)
					rc._control.Enabled = false;
				else
					rc._control.Enabled = true;

				rc._control.Checked = false;
				if (rc._drData["Data"] != System.DBNull.Value)
					rc._control.Checked = (bool)rc._drData["Data"];
			}
		}

		private void ClearNonFieldContextControls()
		{
			_visitDate.IsNullDate = true;
			_patient.Text = "";
			_mrn.Text = "";
			_patientName.Text = "";
			_protocol.Text = "";
			//_spid.Text = "";
			_protocolNumber.Text = "";
			_investigator.Text = "";
		}

		protected override void ResetToOriginal()
		{
			this._formMode = EditMode.Load;

			if (this._fcManager.CurrentRow.RowState == DataRowState.Added || this._fcManager.CurrentRow.RowState == DataRowState.Deleted)
			{
				this._fcManager.DbTable = null;
				this._fcManager.CurrentRow = null;
				this._dtCheckData = null;

				ClearAllControls();
				_form.pnl2.Enabled = false;
				SetFormMode(EditMode.Empty);
			}
			else
			{
				this._fcManager.CurrentRow.RejectChanges();
				foreach (RowContext rc in this._alrcItems)
				{
					rc._drData.RejectChanges();
				}

				DisplayData();
				SetFormMode(EditMode.Read);
			}
		}

		protected override void ClearAllControls()
		{
			base.ClearAllControls();
			ClearNonFieldContextControls();
			//ClearAllCheckData
			foreach (RowContext rc in this._alrcItems)
			{
				rc._control.Checked = false;
				rc._drData = null;
			}
		}

		private void GetVisitPatientProtocolData(int id)
		{
			string visitTable = "";
			int patientID = -1;
			int protocolID = -1;

			if (this._visitType.SelectedIndex == -1)
				return;

			if ((int)this._visitType.SelectedValue == 1)
				visitTable = "ProtocolVisitOutPatient";
			else
				visitTable = "ProtocolVisitAdmission";

			StringBuilder sb = new StringBuilder();
			string sql = "SELECT Patient,Protocol " +
				" FROM " + visitTable +
				" WHERE ID = " + id;


			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql);
				if (reader.Read())
				{
					patientID = reader.GetInt32(0);
					protocolID = reader.GetInt32(1);
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve visit info!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Retrieve Visit Info Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				if (patientID > 0)
					this.GetPatientData(patientID);
				if (protocolID > 0)
					this.GetProtocolData(protocolID);
			}
		}
		#endregion display data

		protected override void SetControlsEnabled(bool enable)
		{
			base.SetControlsEnabled(enable);
			_patient.Enabled = enable;
			_mrn.Enabled = enable;
			_patientName.Enabled = enable;
			_btnVisit.Enabled = enable;
			_protocol.Enabled = enable;
			//_spid.Enabled = enable;
			_protocolNumber.Enabled = enable;
			_investigator.Enabled = enable;
			foreach (RowContext rc in this._alrcItems)
			{
				rc._control.Enabled = enable;
			}

			if (enable)
			{
				if (_patientReaction.Text != "Other")
					_patientReactionOther.Enabled = false;
				if (_painIntervention.Text != "Other")
					_painInterventionOther.Enabled = false;
				if (_ivLocation.Text != "Other")
					_ivLocationOther.Enabled = false;

			}

		}


		public override bool Initialize()
		{
			if (!InitializeCheckFieldsTable())
				return false;
			CreateRowContexts();

			return base.Initialize();
		}


		public override bool GetData(int id)
		{
			StringBuilder sb = new StringBuilder();
			//this works only if there is one key and it is numeric
			//and -1 is not a possible vaule
			string keyFieldName = (string)this._fcManager.TableKeysOrdered[0];
			string sql = "SELECT * FROM " + this._formInfo.TableName +
				" WHERE " + keyFieldName + " =" + id;

			//SqlConnection conn = LoginForm.GetSqlConnection();			
			try
			{
				DataSet ds = DataAccess.GetDataSet(sql);
				DataTable dt = ds.Tables[0];
				if (dt.Rows.Count == 1)
				{
					_fcManager.DbTable = dt;
					_fcManager.CurrentRow = dt.Rows[0];
					this._formMode = Shared.EditMode.Load;
					this._currentPrimaryID = id;

					GetCheckData();
					DisplayData();
					GetGridData(id);
				}
				this.CarryNewClicked(this._chkCarry);

				return true;
			}
			catch (Exception ex)
			{
				sb.Append("Error in retrieving data");
				sb.Append(Environment.NewLine);
				sb.Append(ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Get Data Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				this.ClearCarryData();
				return false;
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();
			}
		}

		private void GetCheckData()
		{
			StringBuilder sb = new StringBuilder();
			string sql = "SELECT * FROM QAFieldData" +
				" WHERE QaID=" + this.CurrentPrimaryID.ToString();

			//SqlConnection conn = LoginForm.GetSqlConnection();

			try
			{
				DataSet ds = DataAccess.GetDataSet(sql);
				_dtCheckData = ds.Tables[0];

				//this could be a newly added field - the field might not
				//be included in the _dtCheckData data table 
				//so we must add a new data row if there is one

				//need a primary key to search for exisiting contextRow
				_dtCheckData.PrimaryKey = new DataColumn[] { _dtCheckData.Columns["FieldID"] };
				CheckForNewFields();

				//iterate through each row and assign row to row context
				foreach (DataRow dr in _dtCheckData.Rows)
				{
					int fieldID = (int)dr["FieldID"];

					//get the associated row context					
					RowContext rc = (RowContext)this._htrcItems[fieldID];
					rc._drData = dr;
				}
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not InitializeCheckFieldsTable()");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this._form, sb.ToString(), "InitializeCheckFieldsTable", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void CheckForNewFields()
		{
			ArrayList alNew = new ArrayList();

			int fieldID;
			DataRow drFound = null;

			foreach (RowContext rc in this._alrcItems)
			{
				fieldID = (int)rc._drField["ID"];
				drFound = _dtCheckData.Rows.Find(fieldID);

				if (drFound == null)
				{
					DataRow drn = this._dtCheckData.NewRow();
					drn["FieldID"] = fieldID;
					drn["QaID"] = this.CurrentPrimaryID;
					drn["Data"] = 0;
					this._dtCheckData.Rows.Add(drn);
					rc._drData = drn;
				}
			}
		}

		public override void New()
		{
			StringBuilder sb = new StringBuilder();
			//this assures us of an empty table
			string sql = "SELECT * FROM " + this._formInfo.TableName +
				" WHERE 1=2";

			string sql2 = "SELECT * FROM QAFieldData WHERE 1=2";

			//SqlConnection conn = LoginForm.GetSqlConnection();
			try
			{
				DataSet ds = DataAccess.GetDataSet(sql);
				DataTable dt = ds.Tables[0];
				_fcManager.DbTable = dt;

				DataRow dr = dt.NewRow();
				dt.Rows.Add(dr);
				_fcManager.CurrentRow = dt.Rows[0];

				SetGridsNew();

				//for checkboxes
				ds = DataAccess.GetDataSet(sql2);
				_dtCheckData = ds.Tables[0];
				InitializeNewCheckDataTable();

				this._formMode = Shared.EditMode.Load;
				this._currentPrimaryID = -1;
				DisplayData();
				GetCarryData();
				GetDefaultData();

				SetFormMode(EditMode.New);
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not create new table.");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this._form, sb.ToString(), "New Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();
			}

		}

		private bool InitializeNewCheckDataTable()
		{
			//initialize an empty check data table
			StringBuilder sb = new StringBuilder();
			string sql = "SELECT * FROM QAFieldData WHERE 1=2";

			//SqlConnection conn = LoginForm.GetSqlConnection();

			try
			{
				DataSet ds = DataAccess.GetDataSet(sql);
				_dtCheckData = ds.Tables[0];

				//use the CheckFields table to get a list of all the checkbox fields
				foreach (DataRow dr in _dtCheckFields.Rows)
				{
					int fieldID = (int)dr["ID"];
					//create a new data row for the field
					DataRow drCkData = _dtCheckData.NewRow();
					drCkData["FieldID"] = fieldID;
					drCkData["Data"] = 0; //initialize to false;

					//get the associated row context
					RowContext rc = (RowContext)this._htrcItems[fieldID];
					rc._drData = drCkData;
					_dtCheckData.Rows.Add(drCkData);
				}
				return true;
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not InitializeCheckFieldsTable()");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this._form, sb.ToString(), "InitializeCheckFieldsTable", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return false;
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();
			}
		}

		private bool InitializeCheckFieldsTable()
		{
			StringBuilder sb = new StringBuilder();
			string sql = "SELECT f.ID,f.Name AS FieldName,f.GroupID,g.Name AS GroupName " +
				"FROM QaFields f INNER JOIN QaGroups g ON f.GroupID = g.ID";

			//SqlConnection conn = LoginForm.GetSqlConnection();

			try
			{
				DataSet ds = DataAccess.GetDataSet(sql);
				_dtCheckFields = ds.Tables[0];
				return true;
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not InitializeCheckFieldsTable()");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this._form, sb.ToString(), "InitializeCheckFieldsTable", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return false;
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();
			}

		}

		private void CreateRowContexts()
		{
			this._alrcItems = new ArrayList();
			this._htrcItems = new Hashtable();
			this._htQaGroups = new Hashtable();

			RowContext rc = null;
			int fieldID = 0;
			int groupID = 0;
			string groupName;

			//for each checkBox field, create the checkbox and assign it
			//to the rightful parent (groupBox)
			foreach (DataRow dr in this._dtCheckFields.Rows)
			{
				//create the row context
				rc = new RowContext();
				fieldID = (int)dr["ID"];
				groupID = (int)dr["GroupID"];
				groupName = dr["GroupName"].ToString();

				CheckBox cb = CreateCheckbox(dr);

				if (cb == null)
					return;

				//cb.Text = fieldName;
				cb.Tag = rc;
				cb.CheckedChanged += new EventHandler(this.Central_CheckedChanged);
				cb.Validating += new CancelEventHandler(checkBox_Validating);

				rc._drField = dr;
				rc._control = cb;
				rc._drData = null;

				this._alrcItems.Add(rc);
				this._htrcItems.Add(fieldID, rc);
				if (!this._htQaGroups.Contains(groupName))
					this._htQaGroups.Add(groupName, groupID);

			}

			//adjust the height of the form contorls based on the longest gxb
			AdjustFormControls();
		}

		private void AdjustFormControls()
		{
			string gbxName;
			Control ctl = null;
			int longest = 0;
			int top = 0;
			int grpLevel = 0;

			_pnlComments = (Panel)Forms.Utils.GetControlByName("pnlComments", this._form.Controls);
			_pnlNotify = (Panel)Forms.Utils.GetControlByName("pnlNotify", this._form.Controls);
			_pnl2 = (Panel)Forms.Utils.GetControlByName("pnl2", this._form.Controls);

			//get the longest groupBox
			foreach (DictionaryEntry de in this._htQaGroups)
			{
				gbxName = "gbx" + de.Value.ToString();
				ctl = (Control)Forms.Utils.GetControlByName(gbxName, this._form.Controls);
				//only get the longest for the qa groups
				grpLevel = Convert.ToInt32(ctl.Tag);
				if (grpLevel > 0)
					continue;
				if (ctl.Height > longest)
				{
					top = ctl.Top;
					longest = ctl.Height;
				}
			}

			_pnlComments.Top = top + longest + 8;
			//_pnl2.Height = _pnlComments.Top + 296;

			//resize the notify section
			//get the longest groupBox
			longest = 0;
			foreach (DictionaryEntry de in this._htQaGroups)
			{
				gbxName = "gbx" + de.Value.ToString();
				ctl = (Control)Forms.Utils.GetControlByName(gbxName, this._form.Controls);
				//only get the longest for the qa groups
				grpLevel = Convert.ToInt32(ctl.Tag);
				if (grpLevel < 1)
					continue;
				if (ctl.Height > longest)
				{
					top = ctl.Top;
					longest = ctl.Height;
				}
			}

			_pnlComments.Height = longest + 200;
			_pnlNotify.Height = longest + 72;
			_pnl2.Height = _pnlComments.Height + _pnlComments.Top;
		}

		private CheckBox CreateCheckbox(DataRow dr)
		{
			int fieldID = (int)dr["ID"];
			int groupID = (int)dr["GroupID"];
			string fieldName = dr["FieldName"].ToString();
			string groupName = dr["GroupName"].ToString();

			string groupCtlName = "gbx" + groupID.ToString();
			GroupBox gbx = (GroupBox)Forms.Utils.GetControlByName(groupCtlName, this._form.Controls);
			CheckBox cb = new CheckBox();
			cb.Parent = gbx;

			int curGbxHeight = gbx.Height;
			gbx.Height += 35;

			Size sz = new Size(220, 32);
			cb.Size = sz;
			cb.Left = 8;
			cb.Top = curGbxHeight;
			cb.Text = fieldName;
			cb.Name = "f" + fieldID.ToString();
			cb.Visible = true;

			if (gbx.Text.StartsWith("groupBox"))
				gbx.Text = groupName;

			return cb;
		}

		private void checkBox_Validating(object sender, CancelEventArgs e)
		{
			CheckBox cb = (CheckBox)sender;
			RowContext rc = (RowContext)cb.Tag;

			rc._drData["Data"] = cb.Checked;
		}

		#region verify
		protected bool VerifyPatientReaction(Control ctl)
		{
			StringBuilder sb = new StringBuilder();
			FieldContext fc = (FieldContext)ctl.Tag;
			int val = 0;
			if (_patientReaction.SelectedValue != null)
				val = (int)_patientReaction.SelectedValue;

			//required
			if (_stickAttempts.Text.Length > 0)
			{
				if (val < 1)
				{
					fc.ErrorMessage = "Patient Reaction is required!";
					return false;
				}
			}
			else //not required                
			{
				if (val > 0)
				{
					sb.Append("Stick attempts is required if Pain Intervention is entered!");
					fc.ErrorMessage = sb.ToString();
					return false;
				}
			}
			return true;
		}

		protected bool VerifyPatientReactionOther(Control ctl)
		{
			StringBuilder sb = new StringBuilder();
			FieldContext fc = (FieldContext)ctl.Tag;
			if (_patientReaction.Text == "Other")
			{
				if (_patientReactionOther.Text.Trim().Length == 0)
				{
					fc.ErrorMessage = "Patient Reaction Other is required!";
					return false;
				}
			}
			return true;
		}

		protected bool VerifyPainIntervention(Control ctl)
		{
			StringBuilder sb = new StringBuilder();
			FieldContext fc = (FieldContext)ctl.Tag;
			int val = 0;
			if (_painIntervention.SelectedValue != null)
				val = (int)_painIntervention.SelectedValue;

			//required
			if (_stickAttempts.Text.Length > 0)
			{
				if (val < 1)
				{
					fc.ErrorMessage = "Pain Intervention is required!";
					return false;
				}
			}
			else //not required                
			{
				if (val > 0)
				{
					sb.Append("Stick attempts is required if Pain Intervention is entered!");
					fc.ErrorMessage = sb.ToString();
					return false;
				}
			}
			return true;
		}

		protected bool VerifyPainInterventionOther(Control ctl)
		{
			StringBuilder sb = new StringBuilder();
			FieldContext fc = (FieldContext)ctl.Tag;
			if (_painIntervention.Text == "Other")
			{
				if (_painInterventionOther.Text.Trim().Length == 0)
				{
					fc.ErrorMessage = "Pain Intervention Other is required!";
					return false;
				}
			}
			return true;
		}

		protected bool VerifyIVLocation(Control ctl)
		{
			StringBuilder sb = new StringBuilder();
			FieldContext fc = (FieldContext)ctl.Tag;
			int val = 0;
			if (_ivLocation.SelectedValue != null)
				val = (int)_ivLocation.SelectedValue;

			//required
			if (_stickAttempts.Text.Length > 0)
			{
				if (val < 1)
				{
					fc.ErrorMessage = "IV Location is required!";
					return false;
				}
			}
			else //not required                
			{
				if (val > 0)
				{
					sb.Append("Stick attempts is required if IV Location is entered!");
					fc.ErrorMessage = sb.ToString();
					return false;
				}
			}
			return true;
		}

		protected bool VerifyIVLocationOther(Control ctl)
		{
			StringBuilder sb = new StringBuilder();
			FieldContext fc = (FieldContext)ctl.Tag;
			if (_ivLocation.Text == "Other")
			{
				if (_ivLocationOther.Text.Trim().Length == 0)
				{
					fc.ErrorMessage = "IV Location Other is required!";
					return false;
				}
			}
			return true;
		}

		protected bool VerifyRecoveryTime(Control ctl)
		{
			FieldContext fc = (FieldContext)ctl.Tag;
			int val = -99;
			if (_recoveryTime.Text.Length > 0)
				val = int.Parse(_recoveryTime.Text);

			//required
			if (_stickAttempts.Text.Length > 0)
			{
				if (val == -99)
				{
					fc.ErrorMessage = "Recovery Time is required!";
					return false;
				}
				if (val < 0)
				{
					fc.ErrorMessage = "Must be a positive value in minutes";
					return false;
				}
			}
			else //not required                
			{
				if (val != -99)
				{
					fc.ErrorMessage = "Stick attempts is required if Recovery Time is entered!";
					return false;
				}
			}
			return true;
		}

		protected bool VerifyPainScore(Control ctl)
		{
			FieldContext fc = (FieldContext)ctl.Tag;
			int val = -99;
			if (_painScore.Text.Length > 0)
				val = int.Parse(_painScore.Text);

			//required
			if (_stickAttempts.Text.Length > 0)
			{
				if (val == -99)
				{
					fc.ErrorMessage = "Pain Score is required!";
					return false;
				}
				if (val > 11 || val < 0)
				{
					fc.ErrorMessage = "Valid range: 0 to 10";
					return false;
				}
			}
			else //not required                
			{
				if (val != -99)
				{
					fc.ErrorMessage = "Stick attempts is required if Pain Score is entered!";
					return false;
				}
			}
			return true;
		}

		protected bool VerifyStickAttempts(Control ctl)
		{
			FieldContext fc = (FieldContext)ctl.Tag;
			if (_stickAttempts.Text.Length == 0)
				return true;
			int val = int.Parse(_stickAttempts.Text);
			if (val > 9 || val < 1)
			{
				fc.ErrorMessage = "Valid range: 1 to 9";
				return false;
			}
			return true;
		}
		#endregion verify

		#region save
		public override bool Save()
		{
			StringBuilder sb = new StringBuilder();
			string message = "";

			//this is used as a parameter for table grid display
			//DbTableChange tableChange = DbTableChange.Update;

			if (this._doSummaryValidate)
			{
				if (!VerifyAll())
					return false;
				if (!VerifyGrids())
					return false;
			}

			Console.WriteLine("RowState brfore save: " + this._fcManager.CurrentRow.RowState.ToString());
			Database db = DatabaseFactory.CreateDatabase();
			using (DbConnection conn = db.CreateConnection())
			{
				try
				{
					conn.Open();
					DbTransaction trans = conn.BeginTransaction();
					if (_formMode == EditMode.New)
					{
						if (CheckDuplicate())
							return false;
						if (CheckWarning())
							return false;
						//tableChange = DbTableChange.Insert;
						if (!SaveNew(out message, db, trans))
						{
							trans.Rollback();
							sb.Append("New record for " + this._formInfo.Name + " could not be saved.");
							sb.Append(Environment.NewLine);
							sb.Append("Error: " + message);
							MessageBox.Show(this._form, sb.ToString(), "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
							return false;
						}
					}
					else if (_formMode == EditMode.Edit)
					{
						if (!Update(out message, db, trans))
						{
							trans.Rollback();
							sb.Append("Update for " + this._formInfo.Name + " could not be saved.");
							sb.Append(Environment.NewLine);
							sb.Append("Error: " + message);
							MessageBox.Show(this._form, sb.ToString(), "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
							return false;
						}
					}

					if (!SaveCheckData(out message, db, trans))
					{
						trans.Rollback();
						sb.Append("Check data record for " + this._formInfo.Name + " could not be saved.");
						sb.Append(Environment.NewLine);
						sb.Append("Error: " + message);
						MessageBox.Show(this._form, sb.ToString(), "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
						return false;
					}

					trans.Commit();
					ResetGrids();
					//confirmation dialog
					MessageBox.Show("Record was saved.", "Save Confirmation",
						MessageBoxButtons.OK, MessageBoxIcon.Information);

					bool shouldClose = (bool)this._configData["CloseOnSave"];

					if (shouldClose)
					{
						this._isClosing = true;
						this._form.Close();
					}
					else
					{
						this._fcManager.CurrentRow.AcceptChanges();
						this._dtCheckData.AcceptChanges();
						SetGridsAcceptChanges();
						SetFormMode(EditMode.Read);
					}
					this.FireTableChange(DbTableChange.Update);
					Console.WriteLine("RowState after save: " + this._fcManager.CurrentRow.RowState.ToString());


				}
				catch (Exception ex)
				{
					//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
					sb.Append("Form could not be saved.");
					sb.Append(Environment.NewLine);
					sb.Append("Error message: " + ex.Message);
					MessageBox.Show(this._form, sb.ToString(), "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
					return false;
				}
				finally
				{
					if (conn != null)
						conn.Dispose();
				}
				return true;
			}
		}

		private bool SaveCheckData(out string message, Database db, DbTransaction trans)
		{
			message = "";

			foreach (RowContext rc in this._alrcItems)
			{
				if (rc._drData.RowState == DataRowState.Added)
				{
					if (!SaveNewCheckDataRow(out message, db, trans, rc._drData))
						return false;
				}
				else
				{
					if (!UpdateCheckDataRow(out message, db, trans, rc._drData))
						return false;
				}
			}
			return true;
		}

		private bool UpdateCheckDataRow(out string message, Database db, DbTransaction trans, DataRow dr)
		{
			message = "";

			//sql 
			string sqlIns = "UPDATE QAFieldData SET Data=@Data " +
				" WHERE QaID=@QaID AND FieldID= @FieldID";

			SqlParameter[] aParams = new SqlParameter[3];
			aParams[0] = new SqlParameter("@Data", SqlDbType.Bit, 0, "Data");
			aParams[0].Value = dr["Data"];
			aParams[1] = new SqlParameter("@QaID", SqlDbType.Int, 0, "QaID");
			aParams[1].Value = this.CurrentPrimaryID;
			aParams[2] = new SqlParameter("@FieldID", SqlDbType.Int, 0, "FieldID");
			aParams[2].Value = dr["FieldID"];


			try
			{
				DbCommand cmd = db.GetSqlStringCommand(sqlIns);
				DataAccess.AddParamArrayToDbCommand(cmd, aParams);

				int i = db.ExecuteNonQuery(cmd, trans);
				return true;
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				message = ex.Message;
				return false;
			}
		}

		private bool SaveNewCheckDataRow(out string message, Database db, DbTransaction trans, DataRow dr)
		{
			message = "";

			//sql insert
			string sqlIns = "INSERT INTO QAFieldData (QaID,FieldID,Data) VALUES(@QaID,@FieldID,@Data)";

			SqlParameter[] aParams = new SqlParameter[3];
			aParams[0] = new SqlParameter("@QaID", SqlDbType.Int, 0, "QaID");
			aParams[0].Value = this.CurrentPrimaryID;
			aParams[1] = new SqlParameter("@FieldID", SqlDbType.Int, 0, "FieldID");
			aParams[1].Value = dr["FieldID"];
			aParams[2] = new SqlParameter("@Data", SqlDbType.Bit, 0, "Data");
			aParams[2].Value = dr["Data"];


			try
			{
				DbCommand cmd = db.GetSqlStringCommand(sqlIns);
				DataAccess.AddParamArrayToDbCommand(cmd, aParams);

				int i = db.ExecuteNonQuery(cmd, trans);
				return true;
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				message = ex.Message;
				return false;
			}
		}

		#endregion save

		internal class RowContext
		{
			internal RowContext()
			{
			}

			internal CheckBox _control = null;
			internal DataRow _drField = null; //holds the field id, name and group
			internal DataRow _drData = null;

			internal bool CurrentValue()
			{
				return _control.Checked;
			}

		}

	}
}
